<?php

namespace App\Service;

use App\Model\EmailLog;
use App\Model\EmailTemplate;
use App\Model\SmsTemplate;
use Exception;
use Hyperf\Context\Context;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use function Hyperf\Support\env;

class EmailService
{
    /**
     * 发送邮件
     * @throws Exception
     * @throws Exception
     */
    public static function send($address, $scene, $data): true
    {
        $template = EmailTemplate::query()->where('scene', $scene)->first();
        if (!$template) {
            throw new Exception('场景消息模板不存在');
        }
        $template['params'] = new_json_decode($template['params']);
        preg_match_all('/\{(\w+)}/', $template['content'], $matches);
        $paramSet = [];
        if (!empty($matches[1])) {
            foreach ($matches[1] as $k) {
                $paramSet[$k] = $data[$k] ?? '';
            }
        }

        $mail = new PHPMailer();
        $mail->CharSet = 'UTF-8';
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->isSMTP();
        $mail->Host = env('SMTP_HOST');
        $mail->SMTPAuth = true;
        $mail->Username = env('SMTP_USERNAME');
        $mail->Password = env('SMTP_PASSWORD');
        $mail->From = env('SMTP_USERNAME');
        $mail->FromName = env('SMTP_FROM');
        $mail->SMTPSecure = 'ssl';
        $mail->Port = env('SMTP_PORT');
        $mail->Timeout = 5;
        if (is_array($address)) {
            foreach ($address as $addr) {
                $mail->addAddress($addr);
            }
        } else {
            $mail->addAddress($address);
        }
        $mail->isHTML();
        $mail->Subject = $template['title'];
        $mail->Body = str_replace(array_keys($paramSet), array_values($paramSet), $template['content']);
        $mail->AltBody = '';
        try {
            $ret = $mail->send();
            if ($ret) {
                EmailLog::create([
                    'scene' => $template['scene'],
                    'userid' => Context::get('userid', 0),
                    'username' => Context::get('username', ''),
                    'email' => is_array($address) ? implode(',', $address) : $address,
                    'content' => str_replace(array_keys($paramSet), array_values($paramSet), $template['content']),
                    'validate_code' => $paramSet['code'] ?? '',
                    'validate_time' => 0,
                    'add_time' => time(),
                ]);
                return true;
            } else {
                throw new Exception($mail->ErrorInfo);
            }
        } catch (Exception $e) {
            throw new Exception('发送失败:' . $e->getMessage());
        }
    }
}